//
//  YMTextViewVC.swift
//  swift_review
//
//  Created by Andrew on 2024/11/24.
//

import UIKit

class YMTextViewVC: UIViewController, UITextViewDelegate {
    
    private let textView: UITextView = {
           let tv = UITextView()
           tv.translatesAutoresizingMaskIntoConstraints = false
           tv.layer.borderColor = UIColor.lightGray.cgColor
           tv.layer.borderWidth = 1.0
           tv.layer.cornerRadius = 8.0
           return tv
       }()
       
   private let charCountLabel: UILabel = {
       let label = UILabel()
       label.translatesAutoresizingMaskIntoConstraints = false
       label.text = "0/100"
       label.textColor = .gray
       return label
   }()
   
   private let maxCharCount = 100 // 最大字数限制
   
   override func viewDidLoad() {
       super.viewDidLoad()
       view.backgroundColor = .white
       
       setupUI()
       
       // 设置代理
       textView.delegate = self
   }
   
   func setupUI() {
       view.addSubview(textView)
       view.addSubview(charCountLabel)
       
       NSLayoutConstraint.activate([
           // TextView 布局
           textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
           textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
           textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
           textView.heightAnchor.constraint(equalToConstant: 150),
           
           // 字数标签布局
           charCountLabel.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 10),
           charCountLabel.trailingAnchor.constraint(equalTo: textView.trailingAnchor)
       ])
   }
   
   // MARK: - UITextViewDelegate
   
   func textViewDidChange(_ textView: UITextView) {
       // 实时更新字数
       let currentText = textView.text ?? ""
       charCountLabel.text = "\(currentText.count)/\(maxCharCount)"
       
       // 限制最大输入字数
       if currentText.count > maxCharCount {
           // 截取到最大字符数
           let limitedText = String(currentText.prefix(maxCharCount))
           textView.text = limitedText
           charCountLabel.text = "\(maxCharCount)/\(maxCharCount)"
       }
   }
}

